package com.jf.hotelreservation.demos.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jf.hotelreservation.demos.oss.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUpload {

    @Autowired
    private AliOSSProperties aliOSSProperties;

    public String uploadFile(MultipartFile multipartFile) throws Exception{
        //获取文件输入流
        InputStream inputStream = multipartFile.getInputStream();
        //创建文件名
        String fileName = UUID.randomUUID() + multipartFile.getOriginalFilename();
        //上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(
                aliOSSProperties.getEndpoint(),
                aliOSSProperties.getAccessKeyId(),
                aliOSSProperties.getAccessKeySecret()
        );
        ossClient.putObject(aliOSSProperties.getBucketName(), fileName, inputStream);
        //文件访问路径
        String url = "https://" + aliOSSProperties.getBucketName()
                + "." + aliOSSProperties.getEndpoint()
                + "/" + fileName;
        //关闭OSSClient
        ossClient.shutdown();
        //返回上传路径
        return url;
    }

}
